<?php

namespace backend\logic\obj;

use backend\models\CostInfo;
use backend\models\HouseFasility;
use backend\models\HouseInfo;
use backend\models\RoomInfo;
use Yii;
use backend\models\HouseResource;
use backend\models\Ridgepole;

/**
 * 这是一个房东对象
 * 当房东使用账户进入到应用时，
 * 房东所使用的一切能力都在此体现，
 * 次对象只负责拓展房东能力，不参与任何逻辑业务，
 * 此能力在业务所需要时则负责提供服务
 *
 */
class Landlord
{
    public $uid;  //房东uid
    public $passwd; //房东密码
    public $head; //头像
    public $resourceId;

    protected static $instance;

    public static function getInstance($config = [])
    {
        self::$instance || self::$instance = new self($config);
        return self::$instance;
    }

    public function init()
    {

    }

    /**
     * 创建房源的动作
     *
     * @access public
     * @param array $data 房源创建所需要的信息
     * @return array 返回类型
     */
    public function createHouseResource($data)
    {
        $resourceInfo = [
            'uid' => $data['uid'],
            'names' => $data['names'],
            'address' => $data['address'],
            'resource_type' => $data['resource_type'],
        ];
        //创建房源
        $res = HouseResource::createHouseResource($resourceInfo);
        if (empty($res->id))
            throw new \Exception('房源名称已存在');

        $data['id'] = $res->id;
        if ($data['resource_type'] == 1) {
            if(empty($data['house_info']))
                throw new \Exception('套房信息不能为空');

            //循环创建套房
            foreach ($data['house_info'] as $k => $v) {
                $v['resource_id'] = $data['id'];
                $info = $v;
                if (isset($info['room_info']))
                    unset($info['room_info']);

                //创建套房表
                $houseId = $this->createHouseInfo($info);
                if (!$houseId)
                    throw new \Exception('信息插入失败');

                if (!empty($v['room_info']) && is_array($v['room_info'])) {
                    //循环创建房子
                    foreach ($v['room_info'] as $kk => $vv) {
                        $vv['house_info_id'] = $houseId;
                        $room = $this->createRoomInfo($vv);
                        if (!$room)
                            throw new \Exception('信息插入失败');
                    }
                }
            }
        } else {
            $ridgepole = $data['ridgepole'];
            $ridgepole['resource_id'] = $data['id'];
            //创建房源用来创建套房信息附属表
            if (!Ridgepole::createRidgepole($ridgepole))
                throw new \Exception('信息插入失败');

            $floor_sum = (int)$ridgepole['floor_sum'];
            $house_num = (int)$ridgepole['house_num'];
            $room_num = (int)$ridgepole['room_num'];
            if(empty($data['house_info'])){
                $data['house_info'] = [
                    [
                        'resource_id'=>null,
                        'apportion'=>[],
                        'cost_ids'=> [],
                        'house_type'=> '2,1',
                        'door_num'=> 0,
                        'house_fasility'=> [],
                        'orientation'=>0,
                        "house_space"=>0,
                        'floor_num'=>0,
                        'area'=> 0,
                        'img_ids'=> 0,
                        'remark'=> '整栋房源',
                        'disperse_type'=>0,
                        'status'=>0,
                        'rent'=>0,
                        'pay_way'=> 0,
                        'room_info'=>0
                    ],
                ];
            }


            foreach ($data['house_info'] as $k => $v) {
                $v['resource_id'] = $data['id'];
                $info = $v;
                if (isset($info['room_info']))
                    unset($info['room_info']);

                for ($i = 0; $i < $floor_sum; $i++) {

                    for ($j=0;$j < $house_num;$j++){

                        $door_num = ($i+1) * 1000 + $j;
                        $floor_num =  (string)$floor_sum.','.(string)$i;

                        $info['door_num'] = $door_num;
                        $info['floor_num'] = $floor_num;
                        //创建套房表
                        $houseId = $this->createHouseInfo($info);
                        if (!$houseId)
                            throw new \Exception('信息插入失败');

                        $room_info = ['house_info_id' => $houseId];

                        $house_type = 2;
                        for($k=0;$k < $house_type;$k++){
                            $this->createRoomInfo($room_info);
                        }
                    }
                }



            }
        }
        return true;
    }

    /*
     * $data = [
    'names'=> $cost_ids['names'], //费用名称
    'cost_type'=> $cost_ids['cost_type'],//  `cost_type` tinyint(3) comment '费用类型',
    'cost_way'=> $cost_ids['cost_way'],//  `cost_way` varchar(100) comment '收费方式，比如现金，支付宝，微信等',
    'charge_mode'=>$cost_ids['charge_mode'] ,//  `charge_mode` tinyint(3) comment '计费方式，每种计费方式对应一个计费公式，0：正常计费模式，1：阶梯计费模式',
    'cost_data'=> json_encode($cost_ids['cost_data']),//  `cost_data` varchar(500) comment '[[0,2,3],[2,5,6],[5,8,8]] 的json用于计算公式的计算数据，json字符串格式，如此便能存储阶段计费数据和正常计费数据',
    'cost_unit'=> $cost_ids['cost_unit'],//  `cost_unit` tinyint(3) comment '费用单位，仅仅用于展示信息，不参与计算公式。0：:度；1：立方米；2：吨；3：元',
    'min'=> $cost_ids['min'],//  `min` int(11) comment '费用最低值。吨/度/立方 (不足'最低值'按'最低值'收)',
    'period'=>$cost_ids['period'] ,//  `period` int(11) comment '收费周期',
    'time'=> $cost_ids['time'],//  `day_time` int(11) comment '收费时间,每个月的几号收钱',
    ];*/
    protected function createHouseInfo($info)
    {
        $arr = [];
        $array = [];
        //套房独有费用清单
        if (!empty($info['cost_ids']) && is_array($info['cost_ids'])) {
            foreach ($info['cost_ids'] as $k => $v) {
                isset($v['cost_data']) && $v['cost_data'] = json_encode($v['cost_data']);
                $arr[] = CostInfo::insertCost($v);
            }
            $info['cost_ids'] = json_encode($arr);
        }
        //分摊费用清单
        if (!empty($info['apportion']) && is_array($info['apportion'])) {
            foreach ($info['apportion'] as $k => $v) {
                isset($v['cost_data']) && $v['cost_data'] = json_encode($v['cost_data']);
                $array[] = CostInfo::insertCost($v);
            }
            $info['apportion'] = json_encode($array);
        }
        //图片对象
        if (!empty($info['house_img']) && is_array($info['house_img'])) {

        }
        //设施对象
        if (!empty($info['house_fasility']) && is_array($info['house_fasility'])) {
            $info['house_fasility'] = json_encode($info['house_fasility']);
        }
        foreach ($info as $k=>$v){
            if(is_array($v))
                $info[$k] = json_encode($v);
        }
        return HouseInfo::createHouseInfo($info);
    }

    protected function createRoomInfo($info)
    {
        $arr = [];
        $array = [];
        //套房独有费用清单
        if (!empty($info['cost_ids']) && is_array($info['cost_ids'])) {
            foreach ($info['cost_ids'] as $k => $v) {
                isset($v['cost_data']) && $v['cost_data'] = json_encode($v['cost_data']);
                $arr[] = CostInfo::insertCost($v);
            }
            $info['cost_ids'] = json_encode($arr);
        }
        //分摊费用清单
        if (!empty($info['apportion']) && is_array($info['apportion'])) {
            foreach ($info['apportion'] as $k => $v) {
                isset($v['cost_data']) && $v['cost_data'] = json_encode($v['cost_data']);
                $array[] = CostInfo::insertCost($v);
            }
            $info['apportion'] = json_encode($array);
        }
        //图片对象
//        if (!empty($info['house_img']) && is_array($info['house_img'])) {
//
//        }
//        //设施对象
        if (!empty($info['house_fasility']) && is_array($info['house_fasility'])) {
            $info['house_fasility'] = json_encode($info['house_fasility']);
        }
        return RoomInfo::createRoomInfo($info);
    }

    /**.
     * 房东提供自己房源列表信息
     *
     * @access public
     * @param uid  参数一的说明
     * @param mixed $mixed 这是一个混合类型
     * @return array 返回类型
     */
    public function showListHouseInfo($uid)
    {
        $houseInfo = HouseResource::showListHouseInfo($uid);
        foreach ($houseInfo as $k => $v) {
            $resourceId = $v['id'];
            if ($v['resource_type'] != 1) {
                // '房源类型。0：整栋房源；1：分散房源',
                $houseCount = HouseInfo::houseCount($resourceId);
                $houseAlreadyToken = HouseInfo::houseAlreadyToken($resourceId);
                $v['house_info']['count'] = $houseCount;
                $v['house_info']['already_token'] = $houseAlreadyToken;
                $v['house_info']['not_rent_out'] = $houseCount - $houseAlreadyToken;
            } else {
                $houseId = HouseInfo::getIdPassResourceId($resourceId);
                $roomCount = RoomInfo::roomCount($houseId);
                $roomAlreadyToken = RoomInfo::roomAlreadyToken($resourceId);
//                $houseInfo[] = $roomCount;
//                $houseInfo[] = $roomAlreadyToken;
                $v['house_info']['count'] = $roomCount;
                $v['house_info']['already_token'] = $roomAlreadyToken;
                $v['house_info']['not_rent_out'] = $roomCount - $roomAlreadyToken;
            }
            $houseInfo[$k] = $v;
        }
        return $houseInfo;
    }

    /**
     * 房东展示自己某一房源的的详细信息
     *
     * @access public
     * @param mixed $arg1 参数一的说明
     * @param mixed $mixed 这是一个混合类型
     * @return array 返回类型
     */
    public function showHouseDetailInfo($houseId)
    {
        $res = HouseInfo::showHouseDetailInfo($houseId);
        if (!empty($res)) {
            foreach ($res as $k => $v) {
                if ($v['disperse_type'] == 1) {
                    //合租类型
                    $roomInfos = RoomInfo::showHouseInfo($v['id']);
                    $v['roomInfos'] = $roomInfos;
                    $res[$k] = $v;
                }else{
                    $v['roomInfos'] = [];
                    $res[$k] = $v;
                }
            }
        }
        return $res;
    }

    /**
     * 房源提供设施选择信息
     *
     * @access public
     * @param mixed $arg1 参数一的说明
     * @param mixed $mixed 这是一个混合类型
     * @return array 返回类型
     */
    public function showFasilityList()
    {
        return HouseFasility::fasilityInfo();
    }
}
